var clickSubmit = false;
layui.use(['form','layer','laydate','table','laytpl','element'],function(){
    var element = layui.element;
    var laydate = layui.laydate;
    var form = layui.form,
    layer = layui.layer,
    $ = layui.jquery,
        laytpl = layui.laytpl,
        table = layui.table;
    var currentIndex = parent.layer.getFrameIndex(window.name);//获取当前窗体索引

    //添加话术包
    form.on('submit(add)', function(formData){
        try{
            if(clickSubmit == true){//防重复提交
                return;
            }
            clickSubmit = true;
            //弹出loading
            var load = layer.msg('数据提交中，请稍候',{icon: 16,time:false,shade:0.8});
            var bo = verification(formData.form,null);
            if(bo){
                var submitData = formData.field;
                var answerArray = $(".allAnswers");
                var appendAnswer = "";
                answerArray.each(function (index, element) {
                    var str = $(element).val();
                    if (str != null && str.trim().length > 0) {
                        appendAnswer += str.trim() + ",";
                    }
                });
                submitData["content"] = appendAnswer.substring(0, appendAnswer.length - 1);
                saveData(submitData,load);
            }else{
                layer.close(load);
            }
        }catch (e){
            layer.msg("操作异常");
        }finally {
            clickSubmit = false;
        }
    });

    function saveData(submitData,load){
        console.log( parent.window.document.getElementById("customAnswerTypeDiv"));
        $.ajax({
            type: "POST",
            url:  baseUrl+'/flowConfig/saveCustomerAnswerWay',
            dataType: 'json',
            data: submitData,
            success: function (data) {
                console.log(data);
                layer.close(load);
                if(data.code<=0){
                    layer.msg(data.msg);
                }else{
                    layer.msg("保存成功");
                    if(parent.window.document.getElementById("customAnswerTypeDiv")!=undefined){
                        parent.loadCustomAnswerType(data);
                    }
                    //关闭本窗体
                    setTimeout(function () {
                        $("#cancel").click();
                    },1000);
                }
            },
            error: function () {
                layer.close(load);
                layer.msg("保存失败");
                return ;
            }
        });
    }

    $('#cancel').on('click',function () {
        currentIndex = parent.layer.getFrameIndex(window.name);//获取当前窗体索引
        parent.layer.close(currentIndex);//执行关闭
    });

    //验证表单
    function verification(form,iframeWin) {
        var config = {
            verify: {
                required: [
                    /[\S]+/
                    , '必填项不能为空'
                ]
                , phone: [
                    /^1\d{10}$|^$/
                    , '请输入正确的手机号'
                ]
                , email: [
                    /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$|^$/
                    , '邮箱格式不正确'
                ]
                , url: [
                    /(^#)|(^http(s*):\/\/[^\s]+\.[^\s]+)/
                    , '链接格式不正确'
                ]
                , number: [
                    /^\d+$|^$/
                    , '只能填写数字'
                ]
                , date: [
                    /^(\d{4})[-\/](\d{1}|0\d{1}|1[0-2])([-\/](\d{1}|0\d{1}|[1-2][0-9]|3[0-1]))*$|^$/
                    , '日期格式不正确'
                ]
                , identity: [
                    /(^\d{15}$)|(^\d{17}(x|X|\d)$|^$)/
                    , '请输入正确的身份证号'
                ]
            }
        };
        formElem = $(form);
        var button = $(this), verify = config.verify, stop = null
            , DANGER = 'layui-form-danger',PROMPT='required_prompt', field = {}
            , verifyElem = formElem.find('*[lay-verify-zdy]')//获取需要校验的元素
            , checkedElem = formElem.find('*[data-required]') //获取复选框
            ,rangeElem = formElem.find('*[data-range]');//获取范围判断的区间值

        //开始校验
        layui.each(verifyElem, function (_, item) {
            var othis = $(this), tips = '';
            var arr = othis.attr('lay-verify-zdy').split(',');
            for (var i in arr) {
                var ver = arr[i];
                var value = othis.val(), isFn = typeof verify[ver] === 'function';
                if(ver == 'number'&&value==''){
                    value = 0;
                }
                othis.removeClass(DANGER);
                if (verify[ver] && (isFn ? tips = verify[ver](value, item) : !verify[ver][0].test(value))) {
                    layer.msg(tips || verify[ver][1], {
                        icon: 5
                        , shift: 6
                    });
                    //非移动设备自动定位焦点
                    if (!layui.device().android && !layui.device().ios) {
                        if(item.type=='text'){
                            item.focus();
                        }else if(item.type=="select-one"){
                            $(item).next("div").find("input").focus();
                            $(item).next("div").find("input").attr("readonly");
                        }
                    }
                    othis.addClass(DANGER);
                    return stop = true;
                }
            }
        });
        if (stop) return false;
        //返回序列化表单元素， JSON 数据结构数据。
        return true;
    }
});


//用于存放关键字的数组
var keyworldArray = [];
//输入关键字,按回车结束
$("#addKeyword").keyup(function (event) {
    //键盘码为13,代表是出车
    if (event.keyCode == 13) {
        //取出内容
        var val = $("#addKeyword").val();
        var reg = /^[\u4E00-\u9FA5A-Za-z0-9]{1,10}$/;
        //判断一波
        if (reg.test(val)) {
            loadKeyWorlds(val);
        } else {
            layer.msg("关键字含有非法字符或者长度超过10");
        }
        //清空输入框
        $("#addKeyword").val("");
    }
});

function loadKeyWorlds(val) {
    console.log("loadKeyWorlds");
    //将关键字存入可以keyword数组
    keyworldArray.push(val.trim());
    //添加关键字小图标
    $("#keywordBox").append("<input  type='button' value='" + val + "\nx' class='layui-btn layui-btn-sm layui-bg-gray displayKeyword' onclick='GotoDeath(this)'/>");
    /**/
    //将数组转化为字符串,以逗号分隔,方便后台接受
    $("#keywords").val(keyworldArray.join(","));
}


//自杀事件删除关键字小图标
function GotoDeath(needDeath) {
    //获取jq的DOM对象
    var addKeyword = $(needDeath);
    //取得内容
    var content = addKeyword.val().substring(0, addKeyword.val().length - 2);
    //取得所在数组的索引
    var deleteIndex = keyworldArray.indexOf(content);
    //假如索引不为空,删
    if (deleteIndex != null) {
        keyworldArray.splice(deleteIndex, 1);
    }
    $("#keywords").val(keyworldArray.join(","));
    addKeyword.remove();
}


//添加标准答案,弹出输入框
function addAnswer(txt) {
    console.log("addAnswer:"+txt);
    var onetoOneAnswer = "<div class='layui-form-item magt3'>"
        + "<label class='layui-form-label '>问法:</label>"
        + "<div class='layui-input-block'>"
        + "<textarea height: auto' class='allAnswers layui-textarea' required lay-verify='required'"
        + " placeholder='请输入分支问法'  onblur='setanswerArray()'>"+txt+"</textarea>"
        + "<input type='button' class='layui-btn layui-btn-sm layui-bg-gray allDelete'"
        + "value='删除' onclick='deleterandfatherDiv(this)'/>"
        + " </div> "
        + "</div>";

    $("#content").before(onetoOneAnswer);
}


//答案框点击删除,删除答案
function deleterandfatherDiv(needToDelete) {
    //删除DIV
    $(needToDelete).parent().parent().remove();
    //重新加载隐藏域数据
    setanswerArray();
}


/**
 * 每次答案框失去焦点,就重新循环遍历,刷新隐藏域的值
 */
function setanswerArray() {
    var answerArray = $(".allAnswers");
    var appendAnswer = "";
    answerArray.each(function (index, element) {
        var str = $(element).val();
        if (str != null && str.trim().length > 0) {
            appendAnswer += str.trim() + ",";
        }
    });
    $("#content").val(appendAnswer.substring(0, appendAnswer.length - 1));
}